/**
 * stdin下文生视频已测试
 * 群聊文本、视频单独输入和混合输入已测试
 */
// import * from 'node-karin'
export default class aiVideo extends plugin{
    constructor() {
        super(
            {
                name: "ai视频生成",
                event: "message",
                priority: -999999999999999999999999,
                rule: [
                    {
                        reg: "#生视频.*",
                        fnc: "makeVideo",
                    },

                ]
            }
        );
        this.img = null

        //this.apiKey = ""
        this.apiKeys = [
            'c56822dd57bc84b1b8d15ec3065a7fc1.k9jnuwHTfGLs7Ucu',
            'b94c040884bdf4df34030ead1da043e8.is1pSJ78HKMiadn9',
            '4836833af41c27b23cd92797fab4dd64.1duVzUcZjoTcY7FY',
        ]
        /**
         * key获取地址：https://bigmodel.cn/usercenter/apikeys
         * 务必替换成自己的key!!
         * 如果提示undefined渲染则说明内置key失效，自行获取即可
         */
    }

    async makeVideo(e) {
        let text = e.msg||null
        let img = null
       
        if (e.img && e.img.length > 0) {
            img = e.img[0]
        }
    //      if (e.source) {
    //   const history = e.isGroup
    //     ? await e.group.getChatHistory(e.source.seq, 1)
    //     : await e.friend.getChatHistory(e.source.time, 1);

    //   const source = history.pop();
    //   img = source.message.filter(i => i.type === "image").map(i => i.url);
    // }
        let match = text.match(/^#生视频(.*)$/);
        if (match) {
            let prompt = match[1].trim();
            console.log("文字prompt识别", prompt);
            console.log("图片img识别", img);
            let res = await this.Video(prompt,img);
            console.log("res", res);
            e.reply([segment.video(res)]);
        }
    }

    Video(prompt, img) {
        return new Promise((resolve, reject) => {
            const apiUrl = 'https://open.bigmodel.cn/api/paas/v4/videos/generations';
            console.log("传入prompt",prompt)
            console.log("传入img",img)
            const requestData = {
                model: 'cogvideox',
                prompt: prompt,
                image_url: img,
            };
            let apiKey = this.getNextApiKey();
            // 首先发送视频生成请求
            fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiKey}`
                },
                body: JSON.stringify(requestData)
            })
                .then(response => response.json())
                .then(data => {
                    const taskId = data.id; // 获取任务订单号
                    const resultUrl = `https://open.bigmodel.cn/api/paas/v4/async-result/${taskId}`;
                    console.log(`使用key${apiKey}`)
                    this.e.reply([`视频${taskId}渲染中`])
                    //console.log("订单号已生成 快去找群u爆金币吧",taskId)
                    // 设置轮询来检查任务状态
                    const interval = setInterval(() => {
                        fetch(resultUrl, {
                            method: 'GET',
                            headers: {
                                'Authorization': `Bearer ${apiKey}`,
                                'Content-Type': 'application/json'
                            }
                        })
                            .then(response => response.json())
                            .then(data => {
                                //console.log('查询状态:', data.task_status);

                                if (data.task_status === 'SUCCESS') {
                                    clearInterval(interval); // 成功后停止轮询
                                    console.log('视频生成成功',data)
                                    const videoResult = data.video_result[0]; // 获取数组中的第一个对象
                                    console.log('视频URL:', videoResult.url);
                                    console.log('封面URL:', videoResult.cover_image_url);
                                    resolve(videoResult.url); // 返回视频URL
                                } else if (data.task_status === 'FAIL') {
                                    clearInterval(interval); // 失败后停止轮询
                                    reject('视频生成失败');
                                }
                            })
                            .catch(error => {
                                clearInterval(interval); // 请求失败后停止轮询
                                reject(`查询失败: ${error}`);
                            });
                    }, 2000); // 每两秒查询一次

                })
                .catch(error => {
                    reject(`请求失败: ${error}`);
                });
        });
    }
    getNextApiKey() {
        const randomIndex = Math.floor(Math.random() * this.apiKeys.length);
        const apiKey = this.apiKeys[randomIndex];
        console.log('负载均衡-散列-使用API key:', apiKey);
        return apiKey;
    }
}
